﻿/* Copyright © 2010 Nolics
Nolics.net and NSQLObjects are trademarks of Nolics.

Microsoft Public License (Ms-PL)

This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.

2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NSQLObjects.Generator.SQLSchema;
using NSQLObjects.Generator.Syntax;

namespace NSQLObjects.Generator.AST
{
    public class Query
    {
        public Query(string name, Globals g) {
            this.QueryName = name;
            Properties = new DBPropertyList();
            this.G = g;
            if (!G.ImportMode)
                G.Queries.Add(name, this);
            Parameters = new DBParameterList();
            UpdateFieldRanges = new List<Tuple<string, string>>();
        }

        public Globals G { get; set; }

        public IEnumerable<DBProperty> UpdatableProperties {
            get {
                return Properties.Where(p => p.QueryOrder > 0 && !p.QueryOnly);
            }
        }
        public DBPropertyList Properties { get; private set; }

        public string QueryName { get; private set; }

        public string QueryInherit { get; set; }

        /// <summary>
        /// This is fetch query
        /// </summary>
        public bool IsFetch { get; set; }

        public string RowClass { get; set; }

        public string QuerySQL { get; set; }

        public string ParsedSQL { get; private set; }

        public int CodeLine { get; set; }

        public Entity BaseEntity { get; private set; }

        public string TableName { get; set; }

        public List<Tuple<string, string>> UpdateFieldRanges { get; private set; }

        public DBParameterList Parameters { get; private set; }

        // public List<string> SqlParameters { get; private set; }

        /// <summary>
        /// Default query order
        /// </summary>
        public string OrderBy { get; set; }

        public bool RowInherits(string entityName) {
            if (!G.Entities.ContainsKey(entityName))
                return false;
            BaseEntity = G.Entities[entityName];
            foreach (DBProperty pr in BaseEntity.Properties) {
                DBProperty prNew = pr.Clone(pr.Name);
                prNew.Attributes = DBPropertyAttributes.Inherited;
                Properties.Add(prNew);
            }
            return true;
        }


        /// <summary>
        /// Parses parameters from SQL statement and quoted " for C# code
        /// </summary>
        /// <returns>Parsed statement</returns>
        private void ParseSQL(Errors er) {
            StringBuilder sb = new StringBuilder();
            StringBuilder sbParam = null;
            for (int i = 0; i < QuerySQL.Length; i++) {
                char ch = QuerySQL[i];
                if (ch == '\r')
                    continue;
                if (ch == '\n') {
                    sb.Append(" \" + ");
                    sb.AppendLine();
                    sb.Append("              \"");
                    continue;
                }
                if (ch == '"') {
                    sb.Append('\\');
                    sb.Append('"');
                } else
                    sb.Append(ch);
                if (ch == '@')
                    sbParam = new StringBuilder();
                else if (Char.IsLetterOrDigit(ch) || ch == '_') {
                    if (sbParam != null)
                        sbParam.Append(ch);
                } else {
                    sbParam = AddParsedParameter(sbParam, er);
                }
            }
            AddParsedParameter(sbParam, er);
            ParsedSQL = sb.ToString();
        }

        private StringBuilder AddParsedParameter(StringBuilder sbParam, Errors er) {
            if (sbParam != null) {
                string parName = sbParam.ToString();
                var par = Parameters.FirstOrDefault(p => p.Name.EQ(parName));
                if (par != null)
                    par.UsedInQuery = true;
                else {
                    if (IsFetch) {
                        Parameters.Add(new DBParameter(parName) { UsedInQuery = true });
                    } else
                        er.SemErr("Query uses parameter {0} that is not defined in query parameters".F(parName));
                }
                sbParam = null;
            }
            return sbParam;
        }

        public void Validate(Errors er, SchemaValidator sv) {
            ParseSQL(er);
            SchemaFieldList fieldList = null;
            try {
                fieldList = sv.GetFields(QuerySQL, Parameters.Where(p => p.UsedInQuery).Select(p2 => p2.Name));
            } catch (Exception ex) {
                er.SemErr(CodeLine, 1, ex.Message);
                return;
            }
            for (int i = 0; i < fieldList.Count; i++) {
                int idx = Properties.FindIndex(dbprop => dbprop.Name.EQ(fieldList[i].Name));
                if (idx >= 0) {
                    if (Properties[idx].QueryOrder > 0)
                        er.SemErr(CodeLine, 1, "Duplicate column {0}".F(Properties[idx].Name));
                    else
                        Properties[idx].QueryOrder = i + 1;
                    continue;
                }
                AddProperty(er, i, fieldList[i]);
            }

            /// Check for non optional fields
            foreach (var prop in Properties.Where(p => p.QueryOrder == 0 && !p.Optional)) {
                er.SemErr(CodeLine, 1, "Query don't have model field {0}".F(prop.Name));
            }

            // Check all fields in update ranges - if no range is given, all fields are update fields
            if (TableName != null) {
                if (!UpdateFieldRanges.Any()) {
                    foreach (var updateProp in Properties)
                        updateProp.QueryOnly = false;
                }
                foreach (var tp in UpdateFieldRanges) {
                    int idx1 = fieldList.FindIndex(sf => sf.Name.EQ(tp.Item1)) + 1;
                    if (idx1 <= 0)
                        er.SemErr(CodeLine, 1, "Can't locate update field {0} from query".F(tp.Item1));
                    int idx2 = idx1;
                    if (tp.Item2 != null) {
                        idx2 = fieldList.FindIndex(sf => sf.Name.EQ(tp.Item2)) + 1;
                        if (idx2 <= 0)
                            er.SemErr(CodeLine, 1, "Can't locate update field {0} from query".F(tp.Item2));
                    }
                    if (idx1 > idx2)
                        er.SemErr(CodeLine, 1, "Check field order for range {0} - {1}".F(tp.Item1, tp.Item2));
                    foreach (var updateProp in Properties.Where(p => p.QueryOrder >= idx1 && p.QueryOrder <= idx2))
                        updateProp.QueryOnly = false;
                }
            }
            if (IsFetch) {
                // Check query properties
                foreach (var par in Parameters.Where(p => p.TypeName == null && p.UsedInQuery)) {
                    int idx = Properties.FindIndex(dbprop => dbprop.Name == par.Name);
                    if (idx < 0)
                        er.SemErr("Fetch uses parameter {0} that is not defined in fetch parameters or result body".F(par.Name));
                }
            }
            // Check that updatable query has at least one compare field
            if (TableName != null && !Properties.Where(p => (p.Roles & FieldRoles.Compare) == FieldRoles.Compare && !p.QueryOnly).Any()) {
                er.SemErr("No compare field(s) defined for updatable query or fetch '{0}'".F(this.QueryName));
            }

            // Check that update statement is (nearly) valid by executing a query over it
            if (TableName == null)
                return;
            ValidateUpdate(er, sv);
        }

        private void ValidateUpdate(Errors er, SchemaValidator sv) {
            StringBuilder updateSql = new StringBuilder();
            foreach (var prop in Properties.Where(p => !p.QueryOnly)) {
                if (updateSql.Length > 0)
                    updateSql.Append(", ");
                updateSql.Append("[");
                updateSql.Append(prop.Name);
                updateSql.Append("]");
                if (prop.ComputeExpr != null) {
                    updateSql.Append(", ");
                    updateSql.Append(prop.ComputeExpr);
                }
            }
            updateSql.Append(" from  [");
            updateSql.Append(TableName);
            updateSql.Append("]");
            try {
                var tmpfieldList = sv.GetFields("select " + updateSql.ToString(), new string[] { });
            } catch (Exception ex) {
                er.SemErr(CodeLine, 1, ex.Message);
                er.SemErr(CodeLine, 1, "Error in update fields: " + updateSql.ToString());
                return;
            }
        }

        private bool AddProperty(Errors er, int i, SchemaField schemaField) {
            if (RowClass == null)
                RowClass = QueryName + "Row";
            DBProperty prop = G.GetDefault(schemaField.Name);
            if (prop == null) {
                prop = G.GetDefaultForType(schemaField.SQLType);
                if (prop == null) {
                    er.SemErr(CodeLine, 1, "No default declare for field {0} type {1}".F(schemaField.Name, schemaField.SQLType));
                    return false;
                } 
            }
            prop = prop.Clone(schemaField.Name);
            Properties.Add(prop);
            prop.QueryOnly = true;
            prop.QueryOrder = i + 1;
            return true;
        }
    }
}
